//
//  ModifyHeadPicViewController.m
//  ShiZiJieProject
//
//  Created by xiaofang wu on 12-4-3.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "ModifyHeadPicViewController.h"
#import "DataSource.h"
#import "wxAppDelegate.h"

@interface ModifyHeadPicViewController ()

- (void) initNavigation;
- (void) initSubView;
- (void) snapPicButtonPress;

- (void) cancelButtonPress;
- (void) finishButtonPress;
@end



@implementation ModifyHeadPicViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/
- (void) dealloc
{
    [_oldHeadPic release];
    [_newHeadPic release];
    [super dealloc];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initSubView];
    [self initNavigation];
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_texture.png"]];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
//    return (interfaceOrientation == UIInterfaceOrientationPortrait);
    return NO;
}

#pragma 
#pragma mark -- class 
- (void) initNavigation
{
    // title
    UILabel* tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 120, 44)];
    [tempLabel setText:@"修改头像"];
    [tempLabel setBackgroundColor:[UIColor clearColor]];
    [tempLabel setTextAlignment:UITextAlignmentCenter];
    [tempLabel setTextColor:[UIColor colorWithRed:111/255.0 green:117/255.0 blue:81/255.0 alpha:1.0]];
    [tempLabel setFont:[UIFont boldSystemFontOfSize:20]];
    self.navigationItem.titleView = tempLabel;
    [tempLabel release];
    tempLabel = nil;
    
    
    UIImage  *backImage  = [UIImage imageNamed:@"btn_back_normal.png"];
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 60, 30);
	[leftButton setBackgroundImage:backImage forState:UIControlStateNormal];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"btn_back_press.png"] forState:UIControlStateHighlighted];
    [leftButton addTarget:self action:@selector(cancelButtonPress) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIBarButtonItem*  leftButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    //[leftButton release];     
    //leftButton     = nil;
    self.navigationItem.leftBarButtonItem = leftButtonItem;    
    [leftButtonItem release];
    leftButtonItem = nil;
    
    
    UIImage  *registImage = [UIImage imageNamed:@"btn_finish_normal.png"];
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 50, 30);
    
	[rightButton setBackgroundImage:registImage forState:UIControlStateNormal];
    [rightButton setBackgroundImage:[UIImage imageNamed:@"btn_finish_press.png"] forState:UIControlStateHighlighted];
    [rightButton addTarget:self action:@selector(finishButtonPress) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem*  rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightButtonItem;    
    [rightButtonItem release];
    rightButtonItem = nil;
}
- (void) initSubView
{
    UIView*  bgView = [[UIView alloc] initWithFrame:CGRectMake(10, 30, 300, 160)];
    [bgView setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:bgView];
    
    _oldHeadPic = [[EGOImageView alloc] initWithFrame:CGRectMake(30, 30, 100, 100)];
    [_oldHeadPic setImage:[UIImage imageNamed:@"bg_user_default.png"]];
    NSString* imageName = [DataSource shareInstance].userInfo.image_filename;
    [_oldHeadPic setImageURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.wxlvtu.com/img.php?filename=%@",imageName]]];
    [bgView addSubview:_oldHeadPic];
    
    UIImageView* arrow = [[UIImageView alloc] initWithFrame:CGRectMake(142, 70, 16, 21)];
    [arrow setImage:[UIImage imageNamed:@"icn_toward.png"]];
    [bgView addSubview:arrow];
    [arrow release];
    arrow = nil;
    _newHeadPic = [[UIImageView alloc] initWithFrame:CGRectMake(170, 30, 100, 100)];
    [_newHeadPic setImage:[UIImage imageNamed:@"bg_user_default.png"]];
    [bgView addSubview:_newHeadPic];
   
    
    UIControl* temp = [[UIControl alloc] initWithFrame:_newHeadPic.frame];
    [temp addTarget:self action:@selector(snapPicButtonPress) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:temp];
    [temp release];
    [bgView release];
    bgView = nil;

}

#pragma 
#pragma mark  user   button  press
- (void) cancelButtonPress
{
    [self.navigationController popViewControllerAnimated:YES];
    
    
}
- (void) finishButtonPress
{
    CoreMsg* msg = [[CoreMsg alloc] init];
    msg.data = PERSONIMAGE;
    msg.ui_delegate = self;
    
    [[NetDataSource shareInstance] postFileTo:@"http://www.wxlvtu.com/?a=do_update_personal_image" postInfo:[NSString stringWithFormat:@"%@/%@",[[DataSource shareInstance] file_getAppCachePath],@"usericon.jpg"] userInfo:msg];
}


#pragma 
#pragma mark   user  action
- (void) snapPicButtonPress
{
    UIActionSheet *menu  = nil;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        menu = [[UIActionSheet alloc]
                initWithTitle: nil
                delegate:self
                cancelButtonTitle:@"Cancel"
                destructiveButtonTitle:nil
                otherButtonTitles:@"从相册中选", @"拍照", nil];
    }
    else
    {
        menu = [[UIActionSheet alloc]
                initWithTitle: nil
                delegate:self
                cancelButtonTitle:@"Cancel"
                destructiveButtonTitle:nil
                otherButtonTitles:@"从相册中选", nil];
    }

    [menu showInView:self.view];
    [menu release];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    printf("User Pressed Button %d\n", buttonIndex + 1);
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        if(buttonIndex == 0)
        {
            UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
            ipc.sourceType =  UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            ipc.delegate = self;
            ipc.allowsEditing = YES; //3.0

            [self presentModalViewController:ipc animated:YES];	
        }
        else if(buttonIndex == 1)
        {
            UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
            ipc.sourceType =  UIImagePickerControllerSourceTypeCamera;
        
            ipc.delegate = self;
            ipc.allowsEditing = YES; //3.0
            [self presentModalViewController:ipc animated:YES];	
        }
    }
    else
    {
        if(buttonIndex == 0)
        {
            UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
            ipc.sourceType =  UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            ipc.delegate = self;
            ipc.allowsEditing = YES; //3.0
            
            [self presentModalViewController:ipc animated:YES];	
        }
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
	UIImage* image = (UIImage*)[info objectForKey:@"UIImagePickerControllerEditedImage"];
	[self dismissModalViewControllerAnimated:YES];
	[picker release];
    _newHeadPic.image = image;
    
    NSString* Path = [NSString stringWithFormat:@"%@/%@",[[DataSource shareInstance] file_getAppCachePath],@"usericon.jpg"];
    [UIImageJPEGRepresentation(image, 0.6f) writeToFile:Path atomically:YES];
}

#pragma -mark DataSourceDelegate

- (void)onDataSourceSucCallback:(CoreMsg *)coreMsg withData:(id)data
{
    if ([coreMsg.data isEqual: PERSONIMAGE]) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"更新头像成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alert.tag = 2001;
        [alert show];
        [alert release];
        
        CoreMsg* msg = [[CoreMsg alloc] init];
        msg.data = PERSONINFO;
        msg.ui_delegate = [wxAppDelegate getAppDelegate];
        
        [[NetDataSource shareInstance] postTo:@"http://www.wxlvtu.com/?a=page_personal_information" postInfo:nil userInfo:msg];
    }
}

- (void)onDataSourceFailCallback:(CoreMsg *)coreMsg withData:(id)data
{
    if ([coreMsg.data isEqual: PERSONIMAGE]) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:data delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alert.tag = 2001;
        [alert show];
        [alert release];
    }
}

@end
